package com.kira.scaffoldmvc.test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class AlternatePrintWithReentrantLock {

    private static final ReentrantLock lock = new ReentrantLock();
    private static final Condition condition1 = lock.newCondition();
    private static final Condition condition2 = lock.newCondition();
    private static final Condition condition3 = lock.newCondition();
    private static int state = 0;
    private static String str = "ABC";
    private static final int print_time = 3;

    public static void main(String[] args) {
        new Thread(() -> print(0, condition1, condition2),"Thread - A").start();
        new Thread(() -> print(1, condition2, condition3),"Thread - B").start();
        new Thread(() -> print(2, condition3, condition1),"Thread - C").start();
    }

    private static void print(int mystate, Condition fromCondtion, Condition toCondition) {
        for (int i = 0; i < print_time; i++) {
            lock.lock();
            try {
                while (mystate != state) {
                    fromCondtion.await();
                }
                System.out.println(str.charAt(mystate));
                state = (state + 1) % 3;
                toCondition.signal();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }finally {
                lock.unlock();
            }
        }
    }


}
    